package detect.parse.tree;

import java.util.*;

import detect.Log;
import detect.parse.tree.token.PositionString;
import detect.parse.tree.token.RawTokenType;
import detect.parse.tree.token.TokenList;
import detect.parse.tree.token.RawTokenType;

public class ConditionExpression extends Expression {
	public List<Expression> subCondExpList=null;
	
	public TreeType getType(){
		return TreeType.ConditionType;
	}
	public ConditionExpression(){
		
	}
	public ConditionExpression(TokenList _tokenList,List<Expression> _subCondExpList){
		tokenList=_tokenList;
		subCondExpList=_subCondExpList;
	}
	
	@Override
	public List<FunctionCallExpression> getSubFunctionCallExpressionList(){
		List<FunctionCallExpression> subFunCallList=new ArrayList<FunctionCallExpression>(subCondExpList.size());
		for(Expression exp: subCondExpList){
			if(exp.getType()==TreeType.FunctionCallType){
				FunctionCallManager.putFunction(exp);
				subFunCallList.add((FunctionCallExpression)exp);
			}
		}
		return subFunCallList;
	}
	
	@Override
	public void findInnerPatterns(){
		for(Expression subCondExp: subCondExpList){
			subCondExp.findInnerPatterns();
			patterns.addAll(subCondExp.patterns);
		}
	}
	
	@Override
	public Expression getExpression(TokenList _tokenList){//(f(g(a,b),c) && k(a)) || d)
		tokenList= _tokenList;
		Log.incIndence();
		Log.printTree(this.getType().toString());
		int funCallStartIndex=-1;
		int rightBraceIndex=-1;
		
		List<Expression> _subCondExpList=new ArrayList<Expression>(5); 
		while(true){
			funCallStartIndex=_tokenList.indexOf("v(",rightBraceIndex);
			if(funCallStartIndex==-1){
				break;
			}
			
			rightBraceIndex=_tokenList.findMatchRightBrace(funCallStartIndex+1,RawTokenType.LPAREN,RawTokenType.RPAREN);			
			PositionString returnVar=null;
			if(funCallStartIndex>=2 && 
					_tokenList.get(funCallStartIndex-1).rawType==RawTokenType.EQ &&
					_tokenList.get(funCallStartIndex-2).rawType==RawTokenType.IDENTIFIER){
				returnVar=_tokenList.get(funCallStartIndex-2);
			}
			Expression exp=	ExpressionFactory.expInstance.getExpression(
								returnVar,
								_tokenList.subList(funCallStartIndex, rightBraceIndex+1));
			_subCondExpList.add(exp);
		}
		Log.decIndence();
		return new ConditionExpression(_tokenList,_subCondExpList);
	}
}
